(function ($) {
	var timer;
	var queDict,sourceData;
	var isAnaly = false;
	var nurseid = '',time=''
	var quesType={'S':'单选题','M':'多选题','B':'填空题','A':'问答题'}
	var backFlag = false
	$.init({
		swipeBack: false,
		beforeback: function(){
			if (backFlag) {
				return true;
			}else{
				return false;
			}
		}
	});
	$.plusReady(function () {
	    baseSetup();
	})
	
	//保存答案
	function saveAllAnswer(){
		getResult()
		var Result = queDict['Result']
		if (Result == '') {
			mui.toast('请先答题')
			return
		}
		var parr = 'V^'+ sourceData['subID']+'^'+mui('#addTime')[0].innerText+'^'+queDict['videoTime']; //V^3||26^00:00:30^00:00:07
		var subParr='^'+queDict['SubRw']+'^'+Result+'^' //: ^3||5^1」2」3^undefined
		var pdict = {'parr':parr,'subParr':subParr}
		console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:SaveDrillTheory','params':JSON.stringify(pdict),'type':'Method'}
		$.DHCWebService(paramDict, function(result) {
			console.log(JSON.stringify(result))
			//success^3||5,3||26||2,0
			var arr = result.msg.split('^')
			if (arr[0] != 'success') {
				mui.toast(result.msg)
				return
			}
			backFlag = true
			$('#backBtn')[0].style.display = 'block'
			$('.btnArea')[0].style.display = 'none'
			isAnaly = true
			updateOneQuesUI()
		}, function(errorStr) {
			mui.toast('请重试')
		});
	}
	function getResult(){
		switch (queDict['SubMode']){
			case 'M':
				var activeDoms = $('.optionsArea .option.dhc-active')
				var nurAns = ''
				for (var i = 0; i < activeDoms.length;i++) {
					nurAns += i
					if (i != activeDoms.length - 1) {
						nurAns += '」'
					}
				}
				if (activeDoms.length == 0) {
					break
				}
				queDict['Result'] = nurAns
				break;
			case 'B':
				var blankDoms = $('.optionsArea .option input')
				var nurAns = ''
				var isAnsed = false
				for (var i = 0; i < blankDoms.length;i++) {
					nurAns += blankDoms[i].value
					if (blankDoms[i].value != '') {
						isAnsed = true
					}
					if (i != blankDoms.length - 1) {
						nurAns += '」'
					}
				}
				if (!isAnsed) {
					break
				}
				queDict['Result'] = nurAns
				break;
			case 'A':
				queDict['Result']= $('#slider textarea')[0].value
				break;
			default:
				break;
		}
	}
	function updateOneQuesUI(){
		var type = queDict['SubMode']; //S单选 M多选 B填空 A问答
		var title = queDict['SubDesc'];
		var sub = queDict['SubSource'];
		var index = 0
		if (type == 'B') {
			var arr = title.split('﹏﹏')
			title = ''
			for (var i= 0; i < arr.length;i++) {
				title += arr[i]
				if (i != arr.length - 1) {
					title += '<div class="blank">（'+(i+1)+'）</div>'
				}
			}
		}
		var html = '<div class="examTitle">'+(index+1)+'、<span class="examType">【'+quesType[type]+'】</span>'+title
		if(sub != ''){
			html += '<span class="subText">（'+sub+'）</span>'
		}
		if (type == 'A') {
			html += '<span class="askText">（人工阅卷）</span>'
		}
		html += '</div>';
		
		var muiScroll = $('.mui-scroll')[0]
		muiScroll.setAttribute('data-type',type)
		muiScroll.innerHTML = html
		switch (type) {
			case 'S':
				createRadioUI(queDict,muiScroll,index);
				break;
			case 'M':
				createCheckboxUI(queDict,muiScroll,index);
				break;
			case 'B':
				createMultiBlankUI(queDict,muiScroll,index);
				break;
			case 'A':
				createAskUI(queDict,muiScroll,index);
				break;
		}
	}
	
	// 单选
	function createRadioUI(oneDict,scrollDom,index){
		scrollDom.classList.remove('analysisMode')
		var option = queDict['SubOption'].split('」')
		var optionsArea = document.createElement('div');
		optionsArea.id = 'ques-'+index
		optionsArea.classList.add('optionsArea');
		scrollDom.appendChild(optionsArea);
		
		var html = ''
		var nurAns = queDict['Result']
		console.log(nurAns)
		for(var i= 0; i < option.length;i++){
			var op = option[i];
			var activeClass=''
			if(nurAns!="" && i == nurAns){
				activeClass='dhc-active'
			}
			var str = String.fromCharCode(64 + parseInt(i+1));
			html += '<div class="option '+activeClass+'">'+
				'<div class="opName nurfont" data-op="'+i+'">'+str+'</div>'+
				'<div class="opTitle">'+op+'</div></div>'
		}
		optionsArea.innerHTML = html;
		if (!isAnaly) {
			var options = optionsArea.querySelectorAll('.option');
			for (var i = 0; i < options.length;i++) {
				options[i].addEventListener('tap',radioOptionTapped);
			}
		}else{//解析部分
			radioOptionAddAnaly(optionsArea,scrollDom,index);
		}
	}
	function radioOptionTapped(){
		var opDom = this
		var parentNode = opDom.parentNode
		var oldActive = parentNode.querySelector('.dhc-active');
		if (oldActive) {
			oldActive.classList.remove('dhc-active');
		}
		opDom.classList.add('dhc-active');
		var nurseAns = opDom.querySelector('.opName').getAttribute('data-op');
		queDict['Result'] = nurseAns
	}
	
	function radioOptionAddAnaly(optionsArea,scrollDom,index){
		var SubAnswer = queDict['SubAnswer']
		var error = optionsArea.querySelector('.dhc-active .opName');
		var userAns = ''
		if (error) {
			userAns = error.innerText
		}
		if (error && error.getAttribute('data-op') != SubAnswer) {
			error.innerHTML = ''
			error.classList.add('nur-error')
		}
		
		var correct = optionsArea.querySelector('.opName[data-op="'+SubAnswer+'"]');
		var correctAns = correct.innerText
		correct.innerHTML = ''
		correct.classList.add('nur-correct')
		
		scrollDom.classList.add('analysisMode')
		var analysisArea = document.createElement('div');
		analysisArea.classList.add('analysisArea');
		scrollDom.appendChild(analysisArea);
		var analysisText = queDict['SubAnalysis'];
		html = '<div class="ansCompare">正确答案：<span class="correctAns">'+correctAns+'</span>&nbsp;&nbsp;'+
				'您的答案：<span class="yourAns">'+userAns+'</span></div>'+
			'<div class="seperateBar"></div>'+
			'<div class="analysisText">解析：<br/>'+analysisText+'</div>'
		analysisArea.innerHTML = html
	}
	
	// 多选
	function createCheckboxUI(oneDict,scrollDom,index){
		scrollDom.classList.remove('analysisMode')
		var option = queDict['SubOption'].split('」')
		var optionsArea = document.createElement('div');
		optionsArea.id = 'ques-'+index
		optionsArea.classList.add('optionsArea');
		scrollDom.appendChild(optionsArea);
		
		var html = ''
		var nurAns = queDict['Result'] 
		for(var i= 0; i < option.length;i++){
			var op = option[i];
			var activeClass=''
			if(nurAns!="" && ('」'+nurAns+'」').indexOf('」'+i+'」') != -1){
				activeClass='dhc-active'
			}
			var str = String.fromCharCode(64 + parseInt(i+1));
			html += '<div class="option '+activeClass+'">'+
				'<div class="opName nurfont" data-op="'+i+'">'+str+'</div>'+
				'<div class="opTitle">'+op+'</div></div>'
		}
		optionsArea.innerHTML = html;
		if (isAnaly) {//解析部分
			checkboxOptionAddAnaly(optionsArea,scrollDom,index);
			return
		}
		var options = optionsArea.querySelectorAll('.option');
		for (var i = 0; i < options.length;i++) {
			options[i].addEventListener('tap',checkBoxOptionTapped);
		}
	}
	function checkBoxOptionTapped(){
		if (this.getAttribute('class').indexOf('dhc-active') != -1) {
			this.classList.remove('dhc-active');
		}else{
			this.classList.add('dhc-active');
		}
	}
	
	function checkboxOptionAddAnaly(optionsArea,scrollDom,index){
		var SubAnswerStr = ','+queDict['SubAnswer']+','
		var errorDoms = optionsArea.querySelectorAll('.dhc-active .opName');
		var userAns = ''
		for (var i = 0; i < errorDoms.length;i++) {
			var errDom = errorDoms[i]
			userAns += errDom.innerHTML
			if (SubAnswerStr.indexOf(','+errDom.getAttribute('data-op')+',') != -1) {
				continue
			}
			errDom.innerHTML = ''
			errDom.classList.add('nur-error')
		}
		var SubAnswer = queDict['SubAnswer'].split(',')
		var correctAns = ''
		for (var i = 0; i < SubAnswer.length;i++) {
			var correct = optionsArea.querySelector('.opName[data-op="'+SubAnswer[i]+'"]');
			correctAns += correct.innerHTML
			correct.innerHTML = ''
			correct.classList.add('nur-correct')
		}
		scrollDom.classList.add('analysisMode')
		var analysisArea = document.createElement('div');
		analysisArea.classList.add('analysisArea');
		scrollDom.appendChild(analysisArea);
		var analysisText = queDict['SubAnalysis'];
		html = '<div class="ansCompare">正确答案：<span class="correctAns">'+correctAns+'</span>&nbsp;&nbsp;'+
				'您的答案：<span class="yourAns">'+userAns+'</span></div>'+
			'<div class="seperateBar"></div>'+
			'<div class="analysisText">解析：<br/>'+analysisText+'</div>'
		analysisArea.innerHTML = html
	}
	
	// 填空
	function createMultiBlankUI(oneDict,scrollDom,index){
		scrollDom.classList.remove('analysisMode')
		var optionsArea = document.createElement('div');
		optionsArea.id = 'ques-'+index
		optionsArea.classList.add('optionsArea');
		scrollDom.appendChild(optionsArea);
		
		var html = ''
		var Result = queDict['Result'].split('」')
		var SubAnswer = queDict['SubAnswer'].split('」')
		for(var i= 0; i< SubAnswer.length;i++){
			var value = Result[i]==undefined?"":Result[i]
			html += '<div class="option"><div class="fillName">（'+(i+1)+'）</div><input type="text" value="'+value+'" /></div>'
		}
		optionsArea.innerHTML = html;
		if (isAnaly) { //解析
			blankAddAnaly(optionsArea,scrollDom,index)
			return
		}
	}
	
	function blankAddAnaly(optionsArea,scrollDom,index){
		var nurAns = queDict['Result'].split('」')
		var standAns = queDict['SubAnswer'].split('」')
		optionsArea.style.display = 'none';
		scrollDom.classList.add('analysisMode')
		var analysisArea = document.createElement('div');
		analysisArea.classList.add('analysisArea');
		scrollDom.appendChild(analysisArea);
		//包含答案即可得分 SubAnsConFlag: "1" 区分大小写		SubAnsCaseFlag: "1"  不区分答案先后顺序 SubAnsOrderFlag: "1"
		var conFlag = queDict['SubAnsConFlag']
		var caseFlag = queDict['SubAnsCaseFlag']
		var orderFlag = queDict['SubAnsOrderFlag']
		html = ''
		var inputs = optionsArea.querySelectorAll('input')
		var title = queDict['SubDesc'];
		var arr = title.split('﹏﹏')
		var ansText = ''
		for (var i= 0; i< inputs.length;i++) {
			ansText += arr[i]
			if (i != arr.length - 1) {
				ansText += '<div class="blank">'+standAns[i]+'</div>'
			}
			var value = inputs[i].value
			html += '<div class="option"><div class="fillName">（'+(i+1)+'）</div>'+
				'<div class="fillText">'+value+'</div>';
			if (compareBlankValue(value,standAns,conFlag,caseFlag,orderFlag,i)) {
				html += '<div class="nurfont nur-correct"></div></div>'
			}else{
				html += '<div class="nurfont nur-error"></div></div>'
			}
		}
		var analysisText = queDict['SubAnalysis']
		html += '<div class="correctFillText">正确答案：<br/>'+ansText+'</div>'+
			'<div class="seperateBar"></div>'+
			'<div class="analysisText">解析：<br/>'+analysisText+'</div>'
		analysisArea.innerHTML = html
	}
	
	function compareBlankValue(value,nurAnsArr,conFlag,caseFlag,orderFlag,index){
		//包含答案即可得分 SubAnsConFlag: "1" 区分大小写		SubAnsCaseFlag: "1"  不区分答案先后顺序 SubAnsOrderFlag: "1"
		if (caseFlag != '1') {
			value = value.toUpperCase()
			var str = nurAnsArr.join('」').toUpperCase()
			nurAnsArr = str.split('」')
		}
		if (orderFlag != '1') { //区分顺序
			var ans = nurAnsArr[index]
			if (conFlag != '1') { //完全一致
				if (value == ans) {
					return 1
				}
			}else{
				if (value.indexOf(ans) != -1) {
					return 1
				}
			}
		}else{
			var str = nurAnsArr.join('」')
			if (conFlag != '1') { //完全一致
				if (('」'+str+'」').indexOf('」'+value+'」') != -1) {
					return 1
				}
			}else{
				if (str.indexOf(value) != -1) {
					return 1
				}
			}
		}
		return 0
	}
	
	// 问答
	function createAskUI(oneDict,scrollDom,index){
		scrollDom.classList.remove('analysisMode')
		var optionsArea = document.createElement('div');
		optionsArea.id = 'ques-'+index
		optionsArea.classList.add('optionsArea');
		scrollDom.appendChild(optionsArea);
		optionsArea.innerHTML = '<textarea></textarea>';
		
		var html = ''
		var Result = queDict['Result']
		var SubAnswer = queDict['SubAnswer']
		if (isAnaly) { //解析
			askAddAnaly(optionsArea,scrollDom,index)
			return
		}
		//确认答案
		optionsArea.querySelector('textarea').value = queDict['Result']
	}
	function askAddAnaly(optionsArea,scrollDom,index){
		//解析部分
		var nurAns = queDict['Result']
		var standAns = queDict['SubAnswer']
		scrollDom.classList.add('analysisMode')
		var analysisArea = document.createElement('div');
		analysisArea.classList.add('analysisArea');
		scrollDom.appendChild(analysisArea);
		html = '<div class="yourAskText">'+nurAns+'</div>'+
			'<div class="correctAskText">参考答案：<br/>'+standAns+'</div>'+
			'<div class="seperateBar"></div>'+
			'<div class="analysisText">解析：<br/>'+queDict['SubAnalysis']+'</div>'+
			'<div class="textTip">批注：</div>'+
			'<div class="notes">'+'缺少批注'+'</div>'+
			'<div class="textTip">分数：<div class="askScore">'+queDict['GetScore']+'</div>分</div>'
		analysisArea.innerHTML = html
	}

	function baseSetup(){
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		var self = plus.webview.currentWebview()
		sourceData = self.sourceData;
		queDict = self.queDict;
		//console.log(JSON.stringify(queDict))
		var perInfo = app.getState()
		nurseid = perInfo['loginPerID']
		
		var reduceTime = $('#addTime')[0]
		reduceTime.innerHTML = '00:00:00'
		// 底部的交卷按钮
		$('.mui-content .btnArea .baseBtn')[0].addEventListener('tap',function(){
			clearInterval(timer)
			mui.confirm('确认交卷吗?','交卷提醒',['取消','确认'],function (e) {
				if (e.index == 1) {
					saveAllAnswer()
				}else{
					setupTimer()
				}
			},'div')
		})
		setupTimer()
		updateOneQuesUI()
	}
	
	function setupTimer(){
		if (timer) {
			clearInterval(timer)
		}
		timer = setInterval(function() {
			var timeBtn =  $('#addTime')[0];
			timeBtn.innerText = hourMinuteSecondPlus(timeBtn.innerText);
		}, 1000);
	}
	
	function clearAllBtnTapped(){
		//单选
		mui('.mui-scroll[data-type="S"] .').each(function (index,element) {
			element.removeEventListener('tap',radioOptionTapped); 
		})
		//多选
		mui('.mui-scroll[data-type="M"] .option').each(function (index,element) {
			element.removeEventListener('tap',checkBoxOptionTapped); 
		})
		mui('.mui-scroll[data-type="M"] .sureAnsBtn').each(function (index,element) {
			element.removeEventListener('tap',checkBoxSureTapped); 
		})
		//填空
		mui('.mui-scroll[data-type="B"] .sureAnsBtn').each(function (index,element) {
			element.removeEventListener('tap',blankSureTapped);
		})
		//问答
		mui('.mui-scroll[data-type="B"]').each(function (index,element) {
			element.removeEventListener('tap',askSureAnsBtnTapped);
		})
	}
})(mui);

/*
包含答案即可得分 SubAnsConFlag: "1"
区分大小写		SubAnsCaseFlag: "1"
不区分答案先后顺序 SubAnsOrderFlag: "1"

{"rw":"24","AnswerDate":"","AnswerTime":"","CreatDate":"2022-09-21","CreatTime":"17:54","Creator":"1","Duration":"50",
"ExamScore":"","ExamTime":"","PaperType":"I","RealPaperType":"I","ReleaseDesc":"测试0921","ReleasePaper":"","ReleasePass":"30",
"Score":"100","Status":"N","ReleaseType":"54||1","ReleaseTypeDesc":"三基","QuestRange":"S」」10」10」100」1,5","StatusDesc":"未答题",
"SubSum":"10","53__1":"10"}]

*/